package main

import (
	"fmt"
	"os"
	"os/exec"
	"syscall"
	"time"
)

func main() {
	if len(os.Args) < 2 {
		println("cleanFront/buildFront/clean/build/buildDocker/pushDocker/buildDockerDev/pushDockerDev")
		return
	}
	action := os.Args[1]
	switch action {
	case "cleanFront":
		cleanFront()
	case "buildFront":
		buildFront()
	case "clean":
		clean()
	case "build":
		build()
	case "buildDocker":
		buildDocker(false)
	case "buildDockerDev":
		buildDocker(true)
	case "pushDocker":
		pushDocker(false)
	case "pushDockerDev":
		pushDocker(true)
	default:
		println("action " + action + " not support")
	}
}

func cleanFront() {
	RunCommand("rm -rf ../assets/build && rm -rf ../statik")
}

func buildFront() {
	cleanFront()
	RunCommand("cd ../assets && yarn install && yarn build")
	RunCommand("go mod download github.com/rakyll/statik && go install github.com/rakyll/statik && " +
		"statik -src=../assets/build/  -include=*.html,*.js,*.json,*.css,*.png,*.svg,*.ico,*.ttf -f -dest ../")
}

func clean() {
	RunCommand("rm -rf ./build/pan")
}

func build() {
	clean()
	RunCommand("go mod tidy")
	RunCommand("go build -o ./build/pan ../")
}

func getUrl(dev bool) string {
	tag := "deploy"
	if dev {
		tag = "dev"
	}
	return fmt.Sprintf("registry.cn-beijing.aliyuncs.com/dream-public/pan:%s_%s",
		tag, time.Now().Format("20060102"))
}

func buildDocker(dev bool) {
	RunCommand(fmt.Sprintf("docker build ../ -f Dockerfile -t %s",
		getUrl(dev)))
}

func pushDocker(dev bool) {
	buildDocker(dev)
	RunCommand(fmt.Sprintf("docker push %s", getUrl(dev)))
}

// RunCommand 运行指令
func RunCommand(command string) {
	println(command)
	cmd := exec.Command("bash", "-c", command)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
	err := cmd.Run()
	if nil != err {
		panic(err)
	}
}
